package cn.zd.demo1;

import static cn.zd.demo1.PermissionActivity.REQUEST_CODE_SMS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MyContentObserverActivity extends AppCompatActivity implements View.OnClickListener {

    private ContentObserver ob;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_content_observer);
        Toast.makeText(this, this.getClass().getName(), Toast.LENGTH_LONG).show();
        tv = findViewById(R.id.tv_info);
        findViewById(R.id.btn_reg).setOnClickListener(this);
        findViewById(R.id.btn_unreg).setOnClickListener(this);
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
            // 没有权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_CODE_SMS);

        } else {
            tv.setText("权限检查通过！");
        }
        ob = new ContentObserver(new Handler(Looper.getMainLooper())) {
            @SuppressLint("Range")
            @Override
            public void onChange(boolean selfChange, @Nullable Uri uri) {
                super.onChange(selfChange, uri);
                // onChange会多次调用，收到一条短信会调用两次
                // content://sms/raw/20 content://sms/inbox/20(content://sms/12033)
                // android 7.0+ 点击标记已读也会回调 content://sms/
                Toast.makeText(MyContentObserverActivity.this,"接收到短信",Toast.LENGTH_SHORT).show();
                Log.i("短信监听",uri.toString());
                if(uri != null && !uri.toString().contains("content://sms/raw/") && !uri.toString().equals("content://sms")) {
                    Toast.makeText(MyContentObserverActivity.this,"接收到短信",Toast.LENGTH_SHORT).show();
                    Cursor cursor = MyContentObserverActivity.this.getContentResolver().query(uri, new String[]{"address", "body", "date"}, null, null, "date DESC");
                    if(cursor.moveToNext()) {
                        String address = cursor.getString(cursor.getColumnIndex("address"));
                        String body = cursor.getString(cursor.getColumnIndex("body"));
                        tv.setText("接收到短信：\n来自："+address+"\n内容："+body);

                    }
                    cursor.close();
                } else {
                    Toast.makeText(MyContentObserverActivity.this,"接收到短信,忽略"+uri.toString(),Toast.LENGTH_SHORT).show();
                }
            }
        };


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_reg) {
            Toast.makeText(this,"开始监听",Toast.LENGTH_SHORT).show();
            // 注册指定uri的观察器，一旦数据发生变化，就触发观察期的onchange方法
            Uri uri = Uri.parse("content://sms");
            // 第二个参数 为false 时表示精确匹配，即只匹配uri,为true时标识可以匹配其派生uri
            // 如上uri，当为false时是监听不到 content://sms/id的
            getContentResolver().registerContentObserver(uri,true, ob);
        } else if (v.getId() == R.id.btn_unreg) {
            Toast.makeText(this,"停止监听",Toast.LENGTH_SHORT).show();
            getContentResolver().unregisterContentObserver(ob);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // permissions权限的清单与grantResults申请结果数组顺序保持一致，可以用于判断多项权限下的具体结果
        switch (requestCode) {
            case REQUEST_CODE_SMS:
                // 短信权限
                StringBuffer info1 = new StringBuffer();
                if (grantResults != null && grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        info1.append("短信授权：第")
                                .append(i)
                                .append("授权结果：")
                                .append(grantResults[i] == PackageManager.PERMISSION_GRANTED ? "已通过" : "未授权");
                    }
                }
                Toast.makeText(this, info1.toString(), Toast.LENGTH_LONG).show();
                break;

        }
    }
}